package com.zb.framework.test.ldap;

import com.google.common.collect.Maps;

import javax.naming.Context;
import javax.naming.Name;
import javax.naming.NamingException;
import javax.naming.directory.*;
import javax.naming.ldap.Control;
import javax.naming.ldap.InitialLdapContext;
import javax.naming.ldap.LdapContext;
import javax.naming.ldap.LdapName;
import java.nio.charset.StandardCharsets;
import java.security.Security;
import java.util.Hashtable;
import java.util.Map;
import java.util.Properties;

/**
 * @author fujianjian
 * @date 2023/5/16 11:38
 **/
public class LdapUtilsBak {

    public static void main(String[] args) {
        // String url = "ldap://10.99.1.12:389";
        // String basedn = "dc=jujingsupply,dc=com";
        // String root = "cn=admin,dc=jujingsupply,dc=com";
        // String passwd = "123123";
        String url = "ldap://10.99.1.20:389";
        String urls = "ldaps://10.99.1.20:636";
        String basedn = "DC=jujingsupply,DC=com";
        String root = "username";
        String passwd = "password";
        LdapContext ctx = ldapConnect(url, root, passwd);
        // LdapContext ctx = ldapsConnect(urls, root, passwd);
        modifyAttribute(Maps.newHashMap(), ctx);
        // LdapContext ctx = personLogin(url);
        // addUser(getLdapUser(), ctx);
        // addHrUser(getHrUser(), ctx);
    }

    public static boolean modifyAttribute(Map<String, String> lu, LdapContext ctx) {

        try {
            String pwd = "qaz@WSX23";
            // Name ldapName = new LdapName("CN=郭迪,OU=品管部,OU=九江大鲸基地,OU=九江市大鲸生物科技有限公司,OU=福建巨鲸生物科技集团有限公司,OU=巨鲸生物科技,DC=jujingsupply,DC=com");
            // Name ldapName = new LdapName("CN=樊满秀,OU=品管部,OU=九江大鲸基地,OU=九江市大鲸生物科技有限公司,OU=福建巨鲸生物科技集团有限公司,OU=巨鲸生物科技,DC=jujin
            //
            //
            // gsupply,DC=com");
            Name ldapName = new LdapName("CN=李金虎,OU=财务部,OU=生鲜江西片区本部,OU=生鲜江西片区,OU=生鲜品业务群,OU=江西正邦食品有限公司,OU=正邦集团,DC=zhengbang,DC=com");
            ModificationItem[] mods = new ModificationItem[2];
            // mods[0] = new ModificationItem(DirContext.REPLACE_ATTRIBUTE, new BasicAttribute("unicodePwd", createUnicodePassword(pwd)));
            mods[0] = new ModificationItem(DirContext.REPLACE_ATTRIBUTE, new BasicAttribute("userAccountControl", "512"));
            mods[1] = new ModificationItem(DirContext.REPLACE_ATTRIBUTE, new BasicAttribute("accountExpires", 0));
            ctx.modifyAttributes(ldapName, mods);
            System.out.println("修改成功");
            return true;
        } catch (Exception e) {
            e.printStackTrace(System.err);
            return false;
        }
    }

    public static byte[] createUnicodePassword(String password) {
        String quotedPassword = "\"" + password + "\"";
        byte[] newUnicodePassword = quotedPassword.getBytes(StandardCharsets.UTF_16LE);
        return newUnicodePassword;

    }

    public static Map<String, String> getLdapUser() {
        Map<String, String> map = Maps.newHashMap();
        map.put("uid", "linjunjie");
        map.put("cn", "linjunjie@stone.com");
        map.put("sn", "linjunjie");
        map.put("userpassword", "123456");
        map.put("displayname", "linjunjie");
        map.put("mail", "linjunjie@stone.com");
        map.put("uidnumber", "1001");
        map.put("gidnumber", "1001");

        return map;
    }

    public static Map<String, String> getHrUser() {
        Map<String, String> map = Maps.newHashMap();
        map.put("distinguishedName", "CN=宋琛01,OU=技术开发组,OU=技术管理组,OU=流程IT部,OU=运营管理中心,OU=正邦科技本部,OU=江西正邦科技股份有限公司,OU=正邦集团,DC=zhengbang,DC=com");
        map.put("uid", "92012344");
        map.put("cn", "宋琛01");
        map.put("name", "宋琛01");
        map.put("ipPhone", "18");
        map.put("sAMAccountName", "linjunjie");
        map.put("title", "高级大数据工程师");
        map.put("mail", "linjunjie@stone.com");
        map.put("wWWHomePage", "1234567890123");
        map.put("mobile", "96110");
        map.put("uidnumber", "1001");
        map.put("gidnumber", "1001");

        return map;
    }

    public static Map<String, String> getLijinhuUser() {
        Map<String, String> map = Maps.newHashMap();
        map.put("distinguishedName", "CN=李金虎,OU=财务部,OU=生鲜江西片区本部,OU=生鲜江西片区,OU=生鲜品业务群,OU=江西正邦食品有限公司,OU=正邦集团,DC=zhengbang,DC=com");
        map.put("uid", "100011");
        map.put("cn", "李金虎");
        map.put("name", "李金虎");
        map.put("ipPhone", "15");
        map.put("sAMAccountName", "lijinhu");
        map.put("title", "销售会计");
        map.put("mail", "lijinhu@zhengbang.com");
        map.put("wWWHomePage", "410782198512285413");
        map.put("mobile", "13782530058");


        return map;
    }


    public static boolean addHrUser(Map<String, String> user, LdapContext context) {
        Attributes attrs = new BasicAttributes();
        BasicAttribute basicAttr = new BasicAttribute("objectclass");
        basicAttr.add("top");
        basicAttr.add("person");
        basicAttr.add("organizationalPerson");
        basicAttr.add("user");
        attrs.put(basicAttr);
        attrs.put("distinguishedName", user.get("distinguishedName"));
        attrs.put("cn", user.get("cn"));
        attrs.put("uid", user.get("uid"));
        attrs.put("description", user.get("name"));
        attrs.put("displayName", user.get("name"));
        attrs.put("ipPhone", user.get("ipPhone"));
        attrs.put("title", user.get("title"));
        attrs.put("sAMAccountName", user.get("sAMAccountName"));
        attrs.put("userPrincipalName", user.get("mail"));
        attrs.put("wWWHomePage", user.get("wWWHomePage"));
        attrs.put("mobile", user.get("mobile"));
        // attrs.put("userAccountControl", "512");
        try {
            String dn = user.get("distinguishedName");
            System.out.println(dn);
            context.createSubcontext(dn, attrs);
            System.out.println("添加用户成功");
            return true;
        } catch (Exception e) {
            System.out.println("添加用户失败");
            e.printStackTrace();
            return false;
        }
    }

    /**
     * 添加用户
     *
     * @param lu
     * @param ctx
     * @return
     */
    public static boolean addUser(Map<String, String> lu, LdapContext ctx) {
        BasicAttributes attrsbu = new BasicAttributes();
        BasicAttribute objclassSet = new BasicAttribute("objectClass");
        // objclassSet.add("account");
        objclassSet.add("posixAccount");
        // objclassSet.add("person");
        // objclassSet.add("organizationalPerson");
        objclassSet.add("inetOrgPerson");
        objclassSet.add("top");
        objclassSet.add("shadowAccount");
        attrsbu.put(objclassSet);
        attrsbu.put("uid", lu.get("uid"));//显示账号
        attrsbu.put("sn", lu.get("sn"));//显示姓名
        attrsbu.put("cn", lu.get("cn"));//显示账号
        attrsbu.put("givenName", lu.get("cn"));//显示账号
        // attrsbu.put("userpassword", lu.get("userpassword"));//显示密码
        attrsbu.put("displayName", lu.get("displayname"));//显示描述
        attrsbu.put("mail", lu.get("mail"));//显示邮箱
        attrsbu.put("homeDirectory", "/home/" + lu.get("uid"));//显示home地址
        attrsbu.put("loginShell", "/bin/bash");//显示shell方式
        attrsbu.put("uidNumber", lu.get("uidnumber"));/*显示id */
        attrsbu.put("gidNumber", lu.get("gidnumber"));/*显示组id */

        try {
            String dn = "uid=" + lu.get("cn") + ",ou=江西巨鲸生物科技有限公司,dc=jujingsupply,dc=com";
            System.out.println(dn);
            ctx.createSubcontext(dn, attrsbu);

            System.out.println("添加用户成功");
            return true;
        } catch (Exception e) {
            System.out.println("添加用户失败");
            e.printStackTrace();
            return false;
        }
    }


    /**
     * 获取ldap认证
     *
     * @param url
     * @param root
     * @param pwd
     * @return
     */
    public static LdapContext ldapConnect(String url, String root, String pwd) {
        String factory = "com.sun.jndi.ldap.LdapCtxFactory";
        String simple = "simple";
        Hashtable<String, String> env = new Hashtable<String, String>();
        env.put(Context.INITIAL_CONTEXT_FACTORY, factory);
        env.put(Context.PROVIDER_URL, url);
        env.put(Context.SECURITY_AUTHENTICATION, simple);
        env.put(Context.SECURITY_PRINCIPAL, root);
        env.put(Context.SECURITY_CREDENTIALS, pwd);
        LdapContext ctx = null;
        Control[] connCtls = null;
        try {
            ctx = new InitialLdapContext(env, connCtls);
            System.out.println("认证成功:" + url);
        } catch (javax.naming.AuthenticationException e) {
            System.out.println("认证失败：");
            e.printStackTrace();
        } catch (Exception e) {
            System.out.println("认证出错：");
            e.printStackTrace();
        }
        return ctx;
    }

    /**
     * 获取ldap认证
     *
     * @param url
     * @param root
     * @param pwd
     * @return
     */
    public static LdapContext ldapsConnect(String urls, String root, String pwd) {
        String factory = "com.sun.jndi.ldap.LdapCtxFactory";
        String simple = "simple";
        Hashtable<String, String> env = new Hashtable<String, String>();
        env.put(Context.INITIAL_CONTEXT_FACTORY, factory);
        env.put(Context.PROVIDER_URL, urls);
        env.put(Context.SECURITY_AUTHENTICATION, simple);
        env.put(Context.SECURITY_PRINCIPAL, root);
        env.put(Context.SECURITY_CREDENTIALS, pwd);
        env.put(Context.AUTHORITATIVE, "true");
        Security.setProperty("jdk.tls.disabledAlgorithms", "");
        System.setProperty("com.sun.jndi.ldap.object.disableEndpointIdentification", "true");

        System.setProperty("javax.net.ssl.trustStore", "C:\\Program Files\\Java\\jdk1.8.0_291\\jre\\lib\\security\\cacerts");
        // System.setProperty("javax.net.ssl.trustStorePassword", "123123");
        env.put(Context.SECURITY_PROTOCOL, "ssl");
        // env.put("java.naming.ldap.factory.socket", "com.zb.framework.ldap.DummySSLSocketFactory");
        LdapContext ctx = null;
        Control[] connCtls = null;
        try {
            ctx = new InitialLdapContext(env, connCtls);
            System.out.println("认证成功:" + urls);
        } catch (javax.naming.AuthenticationException e) {
            System.out.println("认证失败：");
            e.printStackTrace();
        } catch (Exception e) {
            System.out.println("认证出错：");
            e.printStackTrace();
        }
        return ctx;
    }

    public static void main1(String[] args) throws Throwable {
        String url = "ldap://10.99.1.20:389";


        // personLogin(url);
        LdapContext ctx = new InitialLdapContext(init(), null);
        // LdapContext ctx = ldapConnect("ldap://10.89.1.171:389","adsync", "asdfQWER1234");
        // addHrUser(getLijinhuUser(), ctx);
        // modifyAttribute(Maps.newHashMap(), ctx);
        ctx.close();
        // System.out.println("认证成功");
        // modifyAttribute(Maps.newHashMap(), ctx);
    }

    public static Properties init() throws NamingException {
        Properties env = new Properties();
        System.setProperty("com.sun.jndi.ldap.object.disableEndpointIdentification", "true");
        // env.put(Context.SECURITY_PROTOCOL, "ssl");
        // env.put("java.naming.ldap.factory.socket", "com.zb.framework.ldap.DummySSLSocketFactory");
        env.put(DirContext.INITIAL_CONTEXT_FACTORY, "com.sun.jndi.ldap.LdapCtxFactory");
        env.put(Context.PROVIDER_URL, "ldap://10.99.1.20:389");
        env.put(Context.SECURITY_AUTHENTICATION, "simple");
        env.setProperty(Context.REFERRAL, "ignore");
        env.put(Context.SECURITY_PRINCIPAL, "username");
        env.put(Context.SECURITY_CREDENTIALS, "password");
        // env.put(Context.AUTHORITATIVE, "true");
        // env.put("com.sun.jndi.ldap.connect.timeout", "500");
        return env;
    }

    public static Properties initZb() throws NamingException {
        Properties env = new Properties();
        System.setProperty("com.sun.jndi.ldap.object.disableEndpointIdentification", "true");
        // env.put(Context.SECURITY_PROTOCOL, "ssl");
        // env.put("java.naming.ldap.factory.socket", "com.zb.framework.ldap.DummySSLSocketFactory");
        env.put(DirContext.INITIAL_CONTEXT_FACTORY, "com.sun.jndi.ldap.LdapCtxFactory");
        env.put(Context.PROVIDER_URL, "ldap://10.89.1.171:389");
        env.put(Context.SECURITY_AUTHENTICATION, "simple");
        env.setProperty(Context.REFERRAL, "ignore");
        env.put(Context.SECURITY_PRINCIPAL, "username");
        env.put(Context.SECURITY_CREDENTIALS, "password");
        // env.put(Context.AUTHORITATIVE, "true");
        // env.put("com.sun.jndi.ldap.connect.timeout", "500");
        return env;
    }

    public static Properties sslInit() throws NamingException {
        Properties env = new Properties();
        System.setProperty("com.sun.jndi.ldap.object.disableEndpointIdentification", "true");
        // System.setProperty("javax.net.ssl.trustStore", "C:\\Program Files\\Java\\jdk1.8.0_291\\jre\\lib\\security\\cacerts");
        env.put(Context.SECURITY_PROTOCOL, "ssl");
        env.put("java.naming.ldap.factory.socket", "com.zb.framework.ldap.DummySSLSocketFactory");
        env.put(DirContext.INITIAL_CONTEXT_FACTORY, "com.sun.jndi.ldap.LdapCtxFactory");
        env.put(Context.PROVIDER_URL, "ldaps://10.99.1.20:636");
        env.put(Context.SECURITY_AUTHENTICATION, "simple");
        env.setProperty(Context.REFERRAL, "ignore");
        env.put(Context.SECURITY_PRINCIPAL, "username");
        env.put(Context.SECURITY_CREDENTIALS, "password");
        env.put(Context.AUTHORITATIVE, "true");
        // env.put("com.sun.jndi.ldap.connect.timeout", "500");
        return env;
    }

    public static Properties sslInitZb() throws NamingException {
        Properties env = new Properties();
        System.setProperty("com.sun.jndi.ldap.object.disableEndpointIdentification", "true");
        // System.setProperty("javax.net.ssl.trustStore", "C:\\Program Files\\Java\\jdk1.8.0_291\\jre\\lib\\security\\cacerts");
        env.put(Context.SECURITY_PROTOCOL, "ssl");
        env.put("java.naming.ldap.factory.socket", "com.zb.framework.ldap.DummySSLSocketFactory");
        env.put(DirContext.INITIAL_CONTEXT_FACTORY, "com.sun.jndi.ldap.LdapCtxFactory");
        env.put(Context.PROVIDER_URL, "ldaps://10.89.1.171:636");
        env.put(Context.SECURITY_AUTHENTICATION, "simple");
        env.setProperty(Context.REFERRAL, "ignore");
        env.put(Context.SECURITY_PRINCIPAL, "username");
        env.put(Context.SECURITY_CREDENTIALS, "password");
        env.put(Context.AUTHORITATIVE, "true");
        // env.put("com.sun.jndi.ldap.connect.timeout", "500");
        return env;
    }


}
